/**
 * 压缩图片到宽为2048像素
 */
var fs = require("fs");
var im = require("imagemagick");
var srcPath = "./pictures";
var dstPath = "./compressed";
fs.readdir(srcPath, function (err, dirs) {
	if (err)
		return;
	dirs.reduce(function (previous, curr, index) {
		return previous.then(function () {
			return new Promise(function (resolve, reject) {
				fs.mkdir(dstPath + "/" + curr, function (err) {
					if (err)
						reject(err);
					else fs.readdir(srcPath + "/" + curr, function (err, files) {
						if (err)
							reject(err);
						else
							resolve(files.reduce(function (previous, current) {
								return previous.then(function () {
									return new Promise(function (resolve, reject) {
										if (current.indexOf(".txt") === -1)
											im.resize({
												srcPath: srcPath + "/" + curr + "/" + current,
												dstPath: dstPath + "/" + curr + "/" + current,
												width: 4096
											}, function (err, result) {
												if (err)
													reject(err);
												else
													resolve();
											});
									});
								});
							}, Promise.resolve(null)));
					});
				});
			});
		});
	}, Promise.resolve(null)).then(function () {
		console.log("Done.");
	}, function (err) {
		console.log("Failed.");
		console.log(err);
	});
});